package com.dh.leetcode.one;

import com.dh.leetcode.common.TreeNode;
import com.dh.leetcode.common.TreeNodeIterator;
import org.junit.Test;

import java.util.*;

/**
 * @ClassName: _103_binary_tree_zigzag_level_order_traversal
 * @Description: 103. 二叉树的锯齿形层序遍历
 * 给定一个二叉树，返回其节点值的锯齿形层序遍历。（即先从左往右，再从右往左进行下一层遍历，以此类推，层与层之间交替进行）。
 * <p>
 * 例如：
 * 给定二叉树 [3,9,20,null,null,15,7],
 * <p>
 * 3
 * / \
 * 9  20
 * /  \
 * 15   7
 * 返回锯齿形层序遍历如下：
 * <p>
 * [
 * [3],
 * [20,9],
 * [15,7]
 * ]
 * <p>
 * https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
 * @Author: shouzimu
 * @Date: 2020/12/22 9:18
 */
public class _103_binary_tree_zigzag_level_order_traversal {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (null == root) {
            return res;
        }
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        boolean left = true;
        while (!q.isEmpty()) {
            List<Integer> list = new ArrayList<>(q.size());
            int length = q.size();
            for (int i = 0; i < length; i++) {
                TreeNode tree = q.poll();
                list.add(tree.val);
                if (null != tree.left) {
                    q.offer(tree.left);
                }
                if (null != tree.right) {
                    q.offer(tree.right);
                }
            }
            if (!left) {
                Collections.reverse(list);
            }
            left = !left;
            res.add(list);
        }
        return res;
    }

    @Test
    public void zigzagLevelOrderTest() {
        TreeNode treeNode = TreeNodeIterator.initTestTree(new Integer[]{3, 9, 20, null, null, 15, 7});
        List<List<Integer>> list = zigzagLevelOrder(treeNode);
        System.out.println(list);
    }
}
